package two_pointer;

import linkedlist.ListNode;

/**
 * Created with IntelliJ IDEA.
 * Description: 面试题 02.07. 链表相交
 * User: Li_yizYa
 * Date: 2025/5/12
 * Time: 22:35
 */
public class Solution7 {
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode curA = headA;
        ListNode curB = headB;
        int lenA = 0;
        int lenB = 0;
        while (curA != null) {
            curA = curA.next;
            lenA++;
        }
        while (curB != null) {
            curB = curB.next;
            lenB++;
        }
        int len = lenA - lenB;
        if (len > 0) {
            curA = headA;
            curB = headB;
        } else {
            curA = headB;
            curB = headA;
        }
        if (len < 0) {
            len = -len;
        }
        while (len > 0) {
            curA = curA.next;
            len--;
        }
        while (curA != null && curB != null) {
            if (curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        ListNode curA = headA;
        ListNode curB = headB;
        while (curA != curB) {
            curA = curA == null ? headB : curA.next;
            curB = curB == null ? headA : curB.next;
        }
        return curA;
    }
}
